package com.guobox.movies.nasManager;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;

import com.guobox.movies.APP;
import com.guobox.movies.entity.NasEntity;


/**
 * Created by xuxinlei on 2017/12/7.
 */

public class NasManager {
    private static final String ACTION_IP = "com.guobox.multibroadcastservice.action.IP";
    public static final String AUTHORITY = "com.guobox.player.nas.provider";
    private static final Uri Nas_Uri = Uri.parse("content://" + AUTHORITY + "/info");
    static final String NAS_ID = "nasId";
    static final String NAS_IP = "nasIp";
    static final String NAS_NAME = "nasName";
    private Context context;
    private NasIpObserve nasIpObserve;
    private NasIpCallback nasIpCallback;

    public NasManager(Context context) {
        this.context = context;
        nasIpObserve = new NasIpObserve(new Handler(Looper.getMainLooper()),context);
    }

    public void addNasIpCallback(NasIpCallback nasIpCallback) {
        this.nasIpCallback = nasIpCallback;
        nasIpObserve.addCallback(nasIpCallback);
        context.getContentResolver().registerContentObserver(Nas_Uri,true,nasIpObserve);
    }

    public void unRegister() {
        if (nasIpObserve != null) {
            context.getContentResolver().unregisterContentObserver(nasIpObserve);
        }
    }
    public NasEntity getNas() {
        ContentResolver contentResolver = APP.getApplication().getContentResolver();
        Cursor cursor = contentResolver.query(Nas_Uri, new String[]{NAS_NAME, NAS_IP}, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst();
            NasEntity nasEntity = new NasEntity();
            nasEntity.setNasName(cursor.getString(cursor.getColumnIndex(NAS_NAME)));
            nasEntity.setNasIp(cursor.getString(cursor.getColumnIndex(NAS_IP)));
            return nasEntity;
        }
        if (cursor != null) {
            cursor.close();
        }
        return new NasEntity();
    }

    public void searchNas() {
        nasIpCallback.beforeSearchNas();
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.guobox.gbrootservice", "com.guobox.gbrootservice.multibroadcast.SendBroadcastIntentService"));
        intent.setAction(ACTION_IP);
        context.startService(intent);
    }

}
